<template>
  <div class="profile">
    <!-- 导航条 -->
    <van-nav-bar
      left-arrow
      @click-left="$router.back()"
      title="编辑资料"
    ></van-nav-bar>

    <!-- 编辑区 -->
    <van-cell-group>
      <van-cell is-link title="头像" center>
        <van-image
          slot="default"
          width="1.5rem"
          height="1.5rem"
          fit="cover"
          round
          :src="user.photo"
          @click='uploadImg'
        />
        <input type="file"  ref='fileImg' hidden @change='uploadFile'>
      </van-cell>

      <van-cell
        is-link
        title="名称"
        :value="user.name"
        @click="showNameDialog"
      />
      <van-cell
        is-link
        title="性别"
        :value="gender"
        @click="showGender = true"
      />
      <van-cell
        is-link
        title="生日"
        :value="user.birthday"
        @click="showDate"
      />
    </van-cell-group>
    <van-dialog
      v-model="showName"
      title="修改用户名"
      show-cancel-button
      @confirm="saveName"
    >
      <van-field v-model.trim="userName" placeholder="请输入用户名" />
    </van-dialog>
    <van-popup v-model="showGender" position="bottom">
      <van-nav-bar
        title="修改性别"
        left-text="取消"
        @click-left="showGender = false"
      >
      </van-nav-bar>
      <van-cell title="男" @click="saveGender(0)" is-link></van-cell>
      <van-cell title="女" @click="saveGender(1)" is-link></van-cell>
    </van-popup>
     <van-popup v-model="showBirthday" position="bottom"  >
    <van-datetime-picker
      v-model="currentDate"
      type="date"
      title="选择年月日"
      :min-date="minDate"
      :max-date="maxDate"
      @confirm="saveBirthday"
    />
    </van-popup>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { reqGetProfile, reqUpdateUserInfo, reqUpdatePhoto } from '@/api/user'
export default {
  name: 'userProfile',
  data () {
    return {
      // 控制弹层
      showName: false,
      showGender: false,
      showBirthday: false,
      // 当前用户的信息
      user: {},
      userName: '',
      minDate: new Date('1950-1-1'),
      maxDate: new Date(),
      currentDate: new Date('2000-1-1')
    }
  },
  created () {
    this.render()
  },
  computed: {
    gender () {
      return this.user.gender === 0 ? '男' : '女'
    }
  },
  methods: {
    async render () {
      const {
        data: { data }
      } = await reqGetProfile()
      this.user = data
    },
    showNameDialog () {
      this.showName = true
      this.userName = this.user.name
    },
    saveName () {
      if (this.userName.length < 1 || this.userName.length > 7) { return this.$toast.fail('请输入长度为1-7位') }
      try {
        reqUpdateUserInfo({ name: this.userName })
        this.render()
      } catch {
        this.$toast.fail('昵称已存在')
      }
    },
    saveGender (gender) {
      reqUpdateUserInfo({ gender })
      this.render()
      // 关闭弹层
      this.showGender = false
    },
    showDate () {
      this.showBirthday = true
      // this.user.birthday 是字符串 需要处理成时间对象
      this.currentDate = new Date(this.user.birthday)
    },
    async saveBirthday () {
      try {
        const birthday = dayjs(this.currentDate).format('YYYY-MM-DD')
        await reqUpdateUserInfo({
          birthday
        })
        // 更新视图
        this.render()
        this.$toast.success('修改成功')
        this.showBirthday = false
      } catch {
        this.$toast.fail('修改失败')
        this.showBirthday = false
      }
    },
    uploadImg () {
      this.$refs.fileImg.click()
    },
    async uploadFile (e) {
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true, // 禁止背景点击
        loadingType: 'spinner',
        overlay: true, // 添加灰色遮罩
        duration: 0 // 展示时长(ms)，值为 0 时，toast 不会消失默认2s
      })
      const file = e.target.files[0]
      console.log(file)
      if (file.size > 1024 * 200) {
        return this.$toast.fail('图片不能超过200Kb')
      }
      const arr = ['image/png', 'image/jpg', 'image/jpeg']
      if (!arr.includes(file.type)) {
        return this.$toast.fail('仅支持,png,jpg格式图片')
      }
      const fm = new FormData()
      fm.append('photo', file)
      await reqUpdatePhoto(fm)
      this.$toast.success('上传成功')
      this.render()
      e.target.value = ''
    }

  }
}
</script>

<style lang="scss" scoped>
::v-deep .van-icon {
  color: #fff;
}
::v-deep .van-nav-bar__text {
  color: #fff;
}
</style>
